package com.supermap.business.cloud.adv;

import com.alibaba.dubbo.config.annotation.Reference;
import com.supermap.business.cloud.push.MyWebSocket;
import com.supermap.business.push.JpushService;
import com.supermap.business.push.getui.AppPush;
import com.supermap.dataservice.util.JSONUtil;
import com.supermap.dubbo.api.cloud.adv.AdcCloudConment;
import com.supermap.dubbo.api.cloud.adv.AdvCloud;
import com.supermap.dubbo.api.cloud.adv.AdvisoryCloudService;
import com.supermap.dubbo.api.cloud.push.Notice;
import com.supermap.dubbo.api.cloud.push.PushService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author aqua
 * @description
 * @date 2018年11月17 22:29
 * @email 1301584033@qq.com
 */
@Controller
@RequestMapping("/cloud/advinfo")
public class AdvisoryCloudController {

    @Reference(timeout = 1000000)
    private AdvisoryCloudService advisoryCloudService;


    @Autowired
    private JpushService jpushService;

    @Reference(timeout = 100000)
    private PushService pushService;
    /**
     *回去学科
     * */
    @GetMapping("/getSubject")
    @ResponseBody
    public List<Map<String, Object>> getSubject(String userId) {
        return advisoryCloudService.getSubject(userId);
    }
    /**
     *收藏
     * */
    @PutMapping("/insertAdvisoryCollect")
    @ResponseBody
    public JSONUtil insertAdvisoryCollect(String userId,String advId){
        return  advisoryCloudService.insertAdvisoryCollect( userId, advId);
    }


    /**
     * 取消收藏
     * **/
    @DeleteMapping("/delAdvisoryCollect")
    @ResponseBody
    public JSONUtil delAdvisoryCollect(String userId, String advId){
        return  advisoryCloudService.delAdvisoryCollect( userId, advId);
    }

    /**
     *点赞
     * */
    @PutMapping("/insertAdvisoryPraise")
    @ResponseBody
    public JSONUtil insertAdvisoryPraise(String userId,String advId){
        return  advisoryCloudService.insertAdvisoryPraise( userId, advId);
    }

    /**
     * 取消点赞
     * **/
    @DeleteMapping("/delAdvisoryPraise")
    @ResponseBody
    public JSONUtil delAdvisoryPraise(String userId,String advId){
        return advisoryCloudService.delAdvisoryPraise(userId,advId);
    }



    /**
     * 咨询上传
     * */
    @PutMapping("/insertAdvisory")
    @ResponseBody
    public JSONUtil insertAdvisory(@RequestBody  AdvCloud advCloud){
        JSONUtil jsonUtil=advisoryCloudService.insertAdvisory(advCloud);
        String noticetype=pushService.getProductNoticeTypes("quanguoapp2019131xsadwqeq");
        if(jsonUtil.getCode()==200){
            Notice notice = new Notice();
            String dateTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            notice.setUploadtime(dateTime);
            notice.setNoticetype(4);
            notice.setMessageid(jsonUtil.getCountSum());
            notice.setNoticetitle(advCloud.getQuestion());
            notice.setSenduserid(advCloud.getUserId());
            if(advCloud.getExpertId()!=null){
              String userId= advCloud.getExpertId();
                //写入
                notice.setReceiveuserid(userId);
                pushService.putNotice(notice);
                //总数推送
                MyWebSocket.sendInfo(pushService.getReceiveuserIdCount(String.valueOf(userId),noticetype).getJsonStr(),String.valueOf(userId));
                    //推送
//                    String alias[]=this.getNoticeCodeByUserId(userId+"");
//                    if(alias.length>0) {
//                        jpushService.sendPush("有人向您咨询了一个问题", notice.getNoticetitle(), null, alias);
//                    }
                    //个性推送
                 List<String> strings=pushService.getUserCode(userId+"");
                AppPush.UserCodePush(strings,"有人向您咨询了一个问题",notice.getNoticetitle());

            }else{
                //更具区域学科市级专家可推送
                List<String> listUserId=advisoryCloudService.
                        getExpertUserIdByareacodeAndSubjectId(advCloud.getAreacode(),advCloud.getSubjectid());
                for(String userId:listUserId){
                    //入库
                    notice.setReceiveuserid(userId);
                    pushService.putNotice(notice);
                    MyWebSocket.sendInfo(pushService.getReceiveuserIdCount(String.valueOf(userId),noticetype).getJsonStr(),String.valueOf(userId));
                }

                  String userIDs="";
                  for(String str:listUserId){
                      userIDs+=str+",";
                  }
                  userIDs=userIDs.substring( 0,userIDs.lastIndexOf(","));
                List<String> strings=pushService.getUserCode(userIDs);
                AppPush.UserCodePush(strings,"有人向您咨询了一个问题",notice.getNoticetitle());
//                  //统一推送
//                  String alias[]=this.getNoticeCodeByUserId(userIDs);
//                  if(alias.length>0){
//                      jpushService.sendPush("咨询推送",notice.getNoticetitle(),null,alias);
//                  }

            }
        }

        return jsonUtil.setCountSum(0);
    }
    /**
     * 咨询上传
     * 咨询回复
     * */
    @PutMapping("/insertAdvisoryConment")
    @ResponseBody
    public JSONUtil insertAdvisoryConment(@RequestBody  AdcCloudConment adcCloudConment){
        JSONUtil jsonUtil=  advisoryCloudService.insertAdvisoryConment(adcCloudConment);
        String noticetype=pushService.getProductNoticeTypes("quanguoapp2019131xsadwqeq");
        if(jsonUtil.getCode()==200){
            //写入
            Notice notice = new Notice();
            String dateTime=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            notice.setUploadtime(dateTime);
            notice.setNoticetype(5);
            notice.setMessageid(Integer.valueOf(adcCloudConment.getAdvInfoId()));
            notice.setNoticetitle(adcCloudConment.getComment());

            if(adcCloudConment.getReceiveUserId()!=null){
                notice.setReceiveuserid(adcCloudConment.getReceiveUserId());
            }else{
                        //查询出接受者的用户Id//已弃用等影响
                    if(!adcCloudConment.getParentId().equals("-1")&&adcCloudConment.getParentId()!=null){
                        notice.setReceiveuserid(advisoryCloudService.getAdvUserIdByParentId(adcCloudConment.getParentId()));
                    }
                    if(adcCloudConment.getParentId().equals("-1")){
                        notice.setReceiveuserid(advisoryCloudService.getAdvUserIdByAdvId(adcCloudConment.getAdvInfoId()));
                    }
            }

            notice.setSenduserid(adcCloudConment.getUserId());
            pushService.putNotice(notice);
            //app总数推送
            MyWebSocket.sendInfo(pushService.getReceiveuserIdCount(String.valueOf(notice.getReceiveuserid()),noticetype).getJsonStr(),String.valueOf(notice.getReceiveuserid()));
            //推送
//              String userId= pushService.getNoticeCodeByUserId(Integer.valueOf(notice.getReceiveuserid()));
//              if(!userId.equals("")&&userId!=null){
//                  jpushService.sendPush("您收到一条咨询评论",notice.getNoticetitle(),null,userId);
//              }
            List<String> strings=pushService.getUserCode(notice.getReceiveuserid()+"");
            AppPush.UserCodePush(strings,"您收到一条咨询回复消息",notice.getNoticetitle());


        }

        return jsonUtil;
    }


    /**
     * 更多评论
     * */
    /**
     * 取消点赞
     * **/
    @GetMapping("/getPageAdvConmment")
    @ResponseBody
    public JSONUtil getPageAdvConmment(String advId, Integer pageNum, Integer pageSise){
        return advisoryCloudService.getPageAdvConmment(advId,pageNum,pageSise);
    }

    /**
     * 分页查询咨询
     * */
    @GetMapping("/getPageAdvList")
    @ResponseBody
    public JSONUtil getPageAdvList(String areaCode,String userId,String farmId,Integer
            pageNum,Integer pageSise,int type,String loginName,String advId,String expertUserId,String keyName){
        if(expertUserId!=null){
            String huifu=pushService.getNoticeObjectUseridList(Integer.valueOf(expertUserId),5);
            huifu=advisoryCloudService.getAdvIdByAdvCommentId(huifu);
            expertUserId=pushService.getNoticeObjectUseridList(Integer.valueOf(expertUserId),4);
          if(expertUserId!=null&&expertUserId.length()>0){
              expertUserId=expertUserId;

          }
            if(huifu!=null&&huifu.length()>0){
                if(expertUserId!=null&&expertUserId.length()>0){
                    expertUserId+=","+huifu;
                }else{
                    expertUserId=huifu;
                }
            }
        }
       if(expertUserId!=null){
           expertUserId="'"+removesamestring(expertUserId)+"'";
       }
        return advisoryCloudService.getPageAdvList(areaCode,userId,farmId,pageNum,pageSise,type,loginName,advId,expertUserId,keyName);
    }



    /**
     * 转换数组方法
     * */
   public String[] getNoticeCodeByUserId(String userids){
       List<String> alias=new ArrayList<>();
       String users[]=userids.split(",");
       for (String userId:users){
           String user=pushService.getNoticeCodeByUserId(Integer.valueOf(userId));
           if(user!=null&&!user.equals("")){
               alias.add(user);
           }
       }
        if(alias.size()>0){
            String[] array2 = alias.toArray(new String[alias.size()]);
            return  array2;
        }
        return  null;
   }

    private  String removesamestring(String str)
    {
        Set<String> mlinkedset = new LinkedHashSet<>();
        String[] strarray = str.split(",");
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < strarray.length; i++)
        {
            if (!mlinkedset.contains(strarray[i]))
            {
                mlinkedset.add(strarray[i]);
                sb.append(strarray[i] + ",");
            }
        }
        return sb.toString().substring(0, sb.toString().length() - 1);
    }



}
